// 导入http模块:
var http = require('http');
var fs = require("fs");
var path= require('path');
var querystring = require('querystring');
var sql = require('mssql');

// create http server
var server = http.createServer(function (request, response) {

    console.log(request.url);

    // 定义了一个post变量，用于暂存请求体的信息
    var post = '';


    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
    request.on('data', function(chunk){    
        post += chunk;
    });

    // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
    request.on('end', function(){    
        post = querystring.parse(post);
        console.log(post);
        // res.end(util.inspect(post));
        if(request.url==='/list'){
            console.log("list html called!");
            let filePath = path.join(__dirname, 'list.html');
            // step 1: read file index.html
            fs.readFile(filePath,  'utf-8', function (err, data) {
                let li_html="";
                // step 2: connect to the database and fetch some data
                let queryStr = "select top 10 * from dbo.course";
                sql.connect("mssql://sa:sa123@localhost:1433/MyDB").then(
                    function(){   
                        // step 3: construct the data
                        new sql.Request().query(queryStr).then(
                            function(result) {
                                result.recordset.forEach(function(ele, index){
                                    li_html += `<ul>`;
                                    li_html += `<li>${ele.course_id}</li>`;
                                    li_html += `<li>${ele.title}</li>`;
                                    li_html += `<li>${ele.dept_name}</li>`;
                                    li_html += `<li>${ele.credits}</li>`;
                                    li_html += `</ul>`;
                                });
                                data = data.replace('^_^', li_html);
                                response.write(data);
                                response.end();
                            }
    
                        ).catch(
                            function(err) {
                                console.log(err);
                            }
                        )
    
                    }).catch(function(err) {
                        console.log(err);
                    }
                );
    
            });
        }else if (request.url==='/'){
            let filePath = path.join(__dirname, 'myLogin.html');
            // step 1: read file index.html
            fs.readFile(filePath,  'utf-8', function (err, data) {
                response.writeHead(200, {
                    "Content-Type": "text/html"
                });
                response.end(data);
    
            });
        }else if (request.url==='/verify'){
            response.writeHead(200, {
                "Content-Type": "text/html"
            });
            let username = post.name;
            let userpwd = post.pwd;
            let verifyStr = `select * from loginUser where userName='${username}' and pwd='${userpwd}'`;
            console.log(verifyStr);
            sql.connect("mssql://sa:sa123@localhost:1433/MyDB").then(function(){
                new sql.Request().query(verifyStr).then(function(result) {
                    console.log(result.recordset.length);
                    console.log(result.recordset);
                    if(result.recordset.length>0){
                        
                        response.end('ok');
                        //今天发现，当使用Ajax请求时，如果后台进行重定向到其他页面时是无法成功的，
                        // 只能在浏览器地址栏输入才能够实现重定向。
                        //Ajax默认就是不支持重定向的，它是局部刷新，不重新加载页面。
                        // response.writeHead(302, {'Location': 'http://127.0.0.1:8080/list'});
                        // response.end();
                    }
                }).catch();
            }).catch();
            
        }
    });

});

// 
server.listen(8080);

console.log('Server is running at http://127.0.0.1:8080/');